package com.krazevina.luatgiaothong;

import com.sun.lwuit.Form;
import com.sun.lwuit.List;
import java.io.*;
import java.util.*;

public class CIMinuv {
	public static String fileData = "songs.txt";
	public static boolean isNum(String s) {
		try {
			Double.parseDouble(s);
		}
		catch (NumberFormatException nfe) {
			return false;
		}
		return true;
	}
        public static Form ref;
	public static Vector search(String strSearch, int maxElement, boolean checkFull){
		Vector ls = new Vector();
		String[]temp;
		try{
                    InputStream inps;
                    InputStreamReader ir;
                    BufferedReader in;
                    inps = ref.getClass().getResourceAsStream("/ResourceTemp.txt");
                    ir = new InputStreamReader(inps);
                    in = new BufferedReader(ir);
			String strLine;
			while((strLine = in.readLine()) != null){
				if(ls.size() >= maxElement)
					return ls;
				if(isNum(strSearch)){
					temp = split(strLine,",");
					if(temp[0].indexOf(strSearch) == 0)
						ls.addElement(strLine);
				}else{
					temp = split(strLine,"\"");
					if(checkFull){
						if(temp[5].indexOf(strSearch) == 0){
							ls.addElement(strLine);
						}
					}else{
						if(temp[5].indexOf(strSearch) > 0){
							ls.addElement(strLine);
						}
					}
				}
				
			}
			if(checkFull && !isNum(strSearch) && ls.size() < maxElement){
                            Vector templs = search(strSearch, maxElement, false);
                            
                            for(int j=0;j<templs.size();j++)
				ls.addElement(templs.elementAt(j));
			}
			in.close();
			
		}catch (Exception e) {
			// TODO: handle exception
			System.err.print(e.getMessage());
		}
		return ls;
	}
    private static String[] split(String original,String separator) {
        Vector nodes = new Vector();
        int index = original.indexOf(separator);
        while(index>=0) {
            nodes.addElement( original.substring(0, index) );
            original = original.substring(index+separator.length());
            index = original.indexOf(separator);
        }
        nodes.addElement( original );
        String[] result = new String[ nodes.size() ];
        if( nodes.size()>0 ) {
            for(int loop=0; loop<nodes.size(); loop++)
                result[loop] = (String)nodes.elementAt(loop);
        }
        return result;
    }
}
